package mango.service.db.task;

import java.util.Deque;
import java.util.LinkedList;

import mango.Mango;

public class DBTaskManager implements Runnable {

    private static DBTaskManager instance;
    private Deque<DBTaskProcessable> taskQueue;
    private long taskCount;

    private DBTaskManager() {
        taskQueue = new LinkedList<DBTaskProcessable>();
        Thread t = new Thread(this);
        t.setName("DBTaskManager");
        t.start();
    }

    public static DBTaskManager getInstance() {
        if (instance == null) {
            instance = new DBTaskManager();
        }
        return instance;
    }

    private void addTask(DBTaskProcessable task) {
        synchronized (taskQueue) {
            taskQueue.add(task);
            taskCount++;
            taskQueue.notify();
        }
    }

    public static void postTask(int eventId, int subEventId, DataHandler handler,
            DataStruct dataStruct) {
        DBTask task = new DBTask(eventId, subEventId, handler, dataStruct);
        DBTaskManager.getInstance().addTask(task);
    }
    
    public long getTaskCount() {
        return taskCount;
    }

    public void run() {
        while (true) {
            try {
                DBTaskProcessable task = null;
                synchronized (taskQueue) {
                    task = taskQueue.pollFirst();
                    if(task == null) {
                        taskQueue.wait(100);
                    }
                }
                if (task != null) {
                    while(!DBTaskProceser.getInstance().distribute(task)) {
                        Thread.sleep(5);
                    }
                }
            }
            catch (Exception e) {
                Mango.getLog().error("DBTaskManager process task Error ", e);
            }
        }
    }
}
